package org.skydiveapplibrary.ui;

import org.skydiveapplibrary.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.GridView;

public class GalleryGridView extends GridView
{
	private int imageSize = 0;
	private int mHorizontalSpacing = 0;

	// getNumColumns was implemented in Api 11
	// so it's bodged for backwards compatibility
    private int mNumColumns = 2;
	
    public GalleryGridView(Context context, AttributeSet attrs)
	{
    	this(context, attrs, 0);
	}
    
	public GalleryGridView(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ImageGrid);
        int hSpacing = a.getDimensionPixelOffset(
                R.styleable.ImageGrid_horizontalSpacing, 0);
        setHorizontalSpacing(hSpacing);
        mHorizontalSpacing = hSpacing;
        
        int vSpacing = a.getDimensionPixelOffset(
                R.styleable.ImageGrid_verticalSpacing, 0);
        setVerticalSpacing(vSpacing);
	}
	
	public int getImageSize()
	{
		return imageSize;
	}
	
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
    	super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int measuredWidth = widthSize;
        int width = Math.max(measuredWidth, getSuggestedMinimumWidth());
        
        int innerWidth = width - getPaddingLeft() - getPaddingRight();
        int horizontalStride = (innerWidth - mHorizontalSpacing) / getNumColumns();

        imageSize = horizontalStride;
    }
    
    @Override
    public int getNumColumns() {  
        return mNumColumns;
    }
}
